import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hktk_app/dao/industry_dao.dart';
import 'package:hktk_app/util/file_manager.dart';
import 'package:open_file/open_file.dart';
import 'package:url_launcher/url_launcher.dart';

class SaveVideoList extends StatefulWidget {
  SaveVideoList({super.key});

  @override
  State<StatefulWidget> createState() => _SaveVideoListState();
}

class _SaveVideoListState extends State<SaveVideoList> {
  // @override
  // void initState() {
  //   //   initState
  //   super.initState();
  // //   初始化获取对应考试目录下所有视频，支持重命名与删除，一键删除,播放
  //
  // }

  late Future<List<FileSystemEntity>> _filesFuture;

  @override
  void initState() {
    super.initState();
    _filesFuture =
        FileManager.getAppDownloadPath(IndustryDao.getExamKey().examId)
            .then((res) {
      return FileManager.listFilesInDir(res).then((data) {
        //   只保留视频文件
        return data.where((element) {
          return element is File && element.path.endsWith('.mp4');
        }).toList();
      });
    });
  }

  // /storage/emulated/0/Android/data/com.yquestion.zzwx/files/video/34
  void _refreshFiles() {
    setState(() {
      _filesFuture =
          FileManager.getAppDownloadPath(IndustryDao.getExamKey().examId)
              .then((res) {
        return FileManager.listFilesInDir(res).then((data) {
          return data.where((element) {
            return element is File && element.path.endsWith('.mp4');
          }).toList();
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    // 
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          centerTitle: true,
          title: Text('保存的课程视频'),
          actions: [
            IconButton(
              icon: Icon(Icons.refresh),
              onPressed: _refreshFiles,
            )
          ],
        ),
        body: SafeArea(
            child: Container(
          margin: EdgeInsets.all(16),
          child: Column(
            children: [
              Align(
                alignment: Alignment.centerRight,
                child: GestureDetector(onTap: (){
                  showDialog(context: context, builder: (BuildContext context){
                    return AlertDialog(
                      title: Text("提示"),
                      content: Text("当前显示对应考试下视频，不同考试的视频需要切换考试"),
                    );
                  });
                },child: Text("注",style: TextStyle(
                  color: Colors.blue,
                  fontSize: 16
                ),)),
              ),

              SizedBox(
                  height: 1.sh - 120-30,
                  child: FutureBuilder(
                      future: _filesFuture,
                      builder: (BuildContext context, AsyncSnapshot snapshot) {
                        if (snapshot.connectionState ==
                            ConnectionState.waiting) {
                          return Center(child: CircularProgressIndicator());
                        } else if (snapshot.hasError) {
                          return Center(child: Text("错误: ${snapshot.error}"));
                        } else if (!snapshot.hasData ||
                            snapshot.data!.isEmpty) {
                          return Center(child: Text("该目录为空"));
                        } else {
                          List<FileSystemEntity> files = snapshot.data!;
                          return ListView.builder(
                            itemCount: files.length,
                            itemBuilder: (context, index) {
                              FileSystemEntity entity = files[index];
                              String name = entity.path.split('/').last;
                              // String type = FileManager.getType(entity);

                              return ListTile(
                                leading: Icon(
                                  entity is File
                                      ? Icons.insert_drive_file
                                      : Icons.folder,
                                  color: entity is File ? null : Colors.amber,
                                ),
                                title: Text(name),
                                subtitle: Text(entity.path),
                                trailing: PopupMenuButton<String>(
                                  onSelected: (value) async {
                                    if (value == "delete") {
                                      await FileManager.deleteFileOrDir(
                                          entity.path);
                                      _refreshFiles();
                                    } else if (value == "rename") {
                                      TextEditingController controller =
                                          TextEditingController(text: name);
                                      showDialog(
                                        context: context,
                                        builder: (context) {
                                          return AlertDialog(
                                            title: Text("重命名 $name"),
                                            content: TextField(
                                              controller: controller,
                                              decoration: InputDecoration(
                                                  labelText: "新名称"),
                                            ),
                                            actions: [
                                              TextButton(
                                                onPressed:
                                                    Navigator.of(context).pop,
                                                child: Text("取消"),
                                              ),
                                              TextButton(
                                                onPressed: () async {
                                                  String newPath = entity
                                                          .parent.path +
                                                      Platform.pathSeparator +
                                                      controller.text;
                                                  await FileManager
                                                      .renameFileOrDir(
                                                          entity.path, newPath);
                                                  Navigator.of(context).pop();
                                                  _refreshFiles();
                                                },
                                                child: Text("确定"),
                                              ),
                                            ],
                                          );
                                        },
                                      );
                                    } else if (value == "play") {
                                      // canLaunchUrl(Uri.parse(entity.path)).then((value) {
                                      //   if(value){
                                      //     launchUrl(Uri.parse(entity.path));
                                      //   }
                                      //
                                      // });

                                      // 类似于startActivity跳转系统应用
                                      OpenFile.open(entity.path);

                                      // Navigator.pushNamed(context, "/local-video",arguments: {
                                      //   "entity":entity
                                      // });
                                    }
                                  },
                                  itemBuilder: (context) => [
                                    PopupMenuItem(
                                      value: "delete",
                                      child: Text("删除"),
                                    ),
                                    PopupMenuItem(
                                      value: "rename",
                                      child: Text("重命名"),
                                    ),
                                    PopupMenuItem(
                                      value: "play",
                                      child: Text("播放"),
                                    ),
                                  ],
                                ),
                              );
                            },
                          );
                        }
                      }))
            ],
          ),
        )));
  }
}
